package com.snatch.deal.shop.biz.service.impl;

import com.snatch.deal.shop.biz.exception.OrderCreateFailedException;
import com.snatch.deal.shop.biz.exception.StockReduceFaildException;
import com.snatch.deal.shop.biz.exception.StockSoldOutException;
import com.snatch.deal.shop.biz.service.ShopOrderService;
import com.snatch.deal.shop.biz.util.ConstantUtil;
import com.snatch.deal.shop.common.util.RandomUtils;
import com.snatch.deal.shop.store.mapper.ShopOrderMapper;
import com.snatch.deal.shop.store.mapper.ShopStockMapper;
import com.snatch.deal.shop.store.model.ShopOrder;
import com.snatch.deal.shop.store.model.ShopStock;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;

/**
 * Created by hao.g on 18/5/15.
 */
@Service
@Transactional(rollbackFor = Exception.class)
public class ShopOrderServiceImpl implements ShopOrderService {
    @Autowired
    private ShopStockMapper shopStockMapper;

    @Autowired
    private ShopOrderMapper shopOrderMapper;

    @Override
    public boolean createOrder(Long stockId) throws Exception {
        //检查库存数
        ShopStock shopStock = shopStockMapper.getStockCount(stockId);
        if (shopStock.getCount() == 0){
            throw new StockSoldOutException(ConstantUtil.SNATCH_DEAL_FINISHED);
        }

        //扣除库存
        shopStock.setCount(shopStock.getCount() - 1);
        if (shopStockMapper.reduceOneStock(shopStock) == 0){
            throw new StockReduceFaildException(ConstantUtil.STOCK_REDUCE_FAILED);
        }

        //创建订单
        ShopOrder shopOrder = new ShopOrder();
        shopOrder.setOrderId(RandomUtils.random());
        shopOrder.setStockId(shopStock.getStockId());
        shopOrder.setCreatedTime(new Date());
        shopOrder.setModifiedTime(new Date());
        if (shopOrderMapper.createOrder(shopOrder) != 1){
            throw new OrderCreateFailedException(ConstantUtil.ORDER_CREATE_FAILED);
        }

        return true;
    }
}
